package com.lemon.smartsafety.http.service;

import android.content.Context;
import android.util.Log;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.common.CommonVo;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.hidden.HiddenTypePickViewVo;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.safecloud.greendao.HiddenDangerInfo;
import com.lemon.safecloud.greendao.HiddenDangerInfoDao;
import com.lemon.safecloud.greendao.HiddenIndexInfo;
import com.lemon.safecloud.greendao.HiddenLevel;
import com.lemon.safecloud.greendao.HiddenLevelDao;
import com.lemon.safecloud.greendao.HiddenType;
import com.lemon.safecloud.greendao.HiddenTypeDao;
import com.lemon.safecloud.greendao.SelfCheckType;
import com.lemon.safecloud.greendao.SelfCheckTypeDao;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import static com.lemon.smartsafety.app.EventTag.TAG_HIDDEN_INDEX_INFO;
import static com.lemon.smartsafety.app.EventTag.TAG_HIDDEN_SELF_CHECK_TYPE;


/**
 * Created by Cooliean on 16/1/19.
 * 隐患相关的网络请求服务
 */
public class HiddenServices extends BaseHttpServices {


    private static final String TAG = "HiddenServices";

    private SelfCheckTypeDao mSelfCheckTypeDao;
    private HiddenLevelDao   mHiddenLevelDao;

    private HiddenServices(Context context) {
        super(context);
        mSelfCheckTypeDao = AppService.getDBHelper().getDaoSession().getSelfCheckTypeDao();
        mHiddenLevelDao = AppService.getDBHelper().getDaoSession().getHiddenLevelDao();
    }

    public static HiddenServices init() {
        return new HiddenServices(IApplication.context());
    }


    public HiddenServices getHiddenMainIndexInfo() {
        LemonRequestParams params = new LemonRequestParams();
        getHiddenMainIndexInfo(params);
        return this;
    }

    public HiddenServices getHiddenMainIndexInfo(LemonRequestParams params) {
        HandlerCallback<HiddenIndexInfo> callback = new HandlerCallback<HiddenIndexInfo>(TAG_HIDDEN_INDEX_INFO) {
        };
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_MAIN_INDEX_INFO);
        OkHttpUtils.getInstance().post().url(serverUrl).tag(callback.getTag()).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }


    /**
     * 获取隐患自查类型（先尝试网络获取，然后再本地获取）
     *
     * @return
     */
    public HiddenServices getHiddenSelfCheckType() {

        LemonRequestParams params = new LemonRequestParams();
        HandlerCallback<List<SelfCheckType>> callback = new HandlerCallback<List<SelfCheckType>>(TAG_HIDDEN_SELF_CHECK_TYPE) {
        };
        if (!AppUtils.isNetworkAvailable(IApplication.context())) {//如果网络不正常,这里就获取本地
            callback.localCallBack(getAllSelfCheckType());
            return this;
        }
        callback.setInnerCallBack(new HandlerCallback.InnerCallBack<List<SelfCheckType>>() {
            @Override
            public void onInnerCallBack(List<SelfCheckType> data) {
                saveHiddenSelfCheckType(data);
            }
        });
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_SELF_CHECK_TYPE);
        Logger.i(serverUrl);
        Logger.json(params.toString());
        OkHttpUtils.get().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }

    /**
     * 缓存自查类型
     *
     * @param items
     * @return
     */
    public HiddenServices saveHiddenSelfCheckType(List<SelfCheckType> items) {
        try {
            if (items != null && !items.isEmpty()) {
                mSelfCheckTypeDao.deleteAll();
                mSelfCheckTypeDao.insertOrReplaceInTx(items);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 获取本地缓存的所有数据
     *
     * @return
     */
    public List<SelfCheckType> getAllSelfCheckType() {
        List<SelfCheckType> result = mSelfCheckTypeDao.queryBuilder().orderAsc(SelfCheckTypeDao.Properties.TypeId).list();
        if (result == null) {
            return new ArrayList<SelfCheckType>();
        }
        return result;
    }


    /**
     * 获取隐患级别（先尝试网络获取，然后再本地获取）
     *
     * @return
     */
    public HiddenServices getHiddenLevel() {
        LemonRequestParams params = new LemonRequestParams();
        HandlerCallback<List<HiddenLevel>> callback = new HandlerCallback<List<HiddenLevel>>(EventTag.TAG_HIDDEN_LEVEL) {
        };
        if (!AppUtils.isNetworkAvailable(IApplication.context())) {//如果网络不正常,这里就获取本地
            callback.localCallBack(getAllHiddenLevel());
            return this;
        }
        callback.setInnerCallBack(new HandlerCallback.InnerCallBack<List<HiddenLevel>>() {
            @Override
            public void onInnerCallBack(List<HiddenLevel> data) {
                saveHiddenLevel(data);
            }
        });
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_LEVEL);
        OkHttpUtils.get().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }


    /**
     * 缓存缓存级别
     *
     * @param items
     * @return
     */
    public HiddenServices saveHiddenLevel(List<HiddenLevel> items) {
        try {
            if (items != null && !items.isEmpty()) {
                mHiddenLevelDao.deleteAll();
                mHiddenLevelDao.insertOrReplaceInTx(items);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 获取本地缓存的所有数据
     *
     * @return
     */
    public List<HiddenLevel> getAllHiddenLevel() {
        List<HiddenLevel> result = mHiddenLevelDao.queryBuilder().orderAsc(HiddenLevelDao.Properties.LevelId).list();
        if (result == null) {
            return new ArrayList<HiddenLevel>();
        }
        return result;
    }


    /**
     * 获取隐患分类（先尝试网络获取，然后再本地获取）
     *
     * @return
     */
    public HiddenServices getHiddenCategory() {
        LemonRequestParams params = new LemonRequestParams();
        HandlerCallback<List<HiddenType>> callback = new HandlerCallback<List<HiddenType>>(EventTag.TAG_HIDDEN_TYPE) {
        };
        if (!AppUtils.isNetworkAvailable(IApplication.context())) {//如果网络不正常,这里就获取本地
            callback.localCallBack(getAllLocalHiddenType());
            return this;
        }
        callback.setInnerCallBack(new HandlerCallback.InnerCallBack<List<HiddenType>>() {
            @Override
            public void onInnerCallBack(List<HiddenType> data) {
                saveHiddenType(data);
            }
        });
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_TYPE_ALL);
        Logger.i(serverUrl);
        Logger.json(params.toString());
        OkHttpUtils.get().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }

    public static ArrayList<HiddenType> getHiddenTypeOneLevel(List<HiddenType> items) {
        if (items == null || items.size() == 0) {
            return new ArrayList<>();
        }
        ArrayList<HiddenType> result = new ArrayList<>();

        for (int i = 0; i < items.size(); i++) {
            HiddenType type = items.get(i);
            if (type.getParentId() == -1) {
                result.add(type);
            }
        }
        return result;
    }

    /**
     * 获取隐患分类选择视图的数据
     *
     * @param items
     * @return
     */
    public static HiddenTypePickViewVo getHiddenTypePickViewVo(List<HiddenType> items) {
        HiddenTypePickViewVo resultVo = new HiddenTypePickViewVo();
        if (items == null || items.size() == 0) {
            return resultVo;
        }
        ArrayList<HiddenType> one  = getHiddenTypeOneLevel(items);
        ArrayList<HiddenType> temp = getHiddenTypeOneLevel(items);

        ArrayList<ArrayList<HiddenType>> two = new ArrayList<>();
        if (temp != null && temp.size() != 0) {
            for (int i = 0; i < temp.size(); i++) {
                HiddenType            type        = temp.get(i);
                ArrayList<HiddenType> queryResult = getByParentId(type.getTypeId());
                if (queryResult != null && queryResult.size() != 0) {
                    two.add(queryResult);
                } else {
                    one.remove(i);//对应项目没有数据支持就移除
                }
            }
        }
        resultVo.setOneLevel(one);
        resultVo.setTwoLevel(two);
        return resultVo;
    }

    public static ArrayList<HiddenType> getByParentId(int parentId) {
        HiddenTypeDao hiddenTypeDao = AppService.getDBHelper().getDaoSession().getHiddenTypeDao();
        return (ArrayList<HiddenType>) hiddenTypeDao.queryBuilder().where(HiddenTypeDao.Properties.ParentId.eq(parentId)).list();
    }


    /**
     * 缓存隐患分类
     *
     * @param items
     * @return
     */
    public HiddenServices saveHiddenType(List<HiddenType> items) {
        HiddenTypeDao hiddenTypeDao = AppService.getDBHelper().getDaoSession().getHiddenTypeDao();
        try {
            if (items != null && !items.isEmpty()) {
                hiddenTypeDao.deleteAll();
                hiddenTypeDao.insertOrReplaceInTx(items);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }


    /**
     * 获取本地缓存的所有数据
     *
     * @return
     */
    public List<HiddenType> getAllLocalHiddenType() {
        HiddenTypeDao    hiddenTypeDao = AppService.getDBHelper().getDaoSession().getHiddenTypeDao();
        List<HiddenType> result        = hiddenTypeDao.queryBuilder().orderAsc(HiddenTypeDao.Properties.ClassId).list();
        if (result == null) {
            return new ArrayList<HiddenType>();
        }
        return result;
    }


    /**
     * 保存隐患消息
     *
     * @return
     */
    public HiddenServices saveHiddenInfoAction(LemonRequestParams params, boolean isEdit) {
        HandlerCallback<CommonVo> callback = new HandlerCallback<CommonVo>(EventTag.TAG_HIDDEN_SAVE_ACTION) {
        };
        String serverUrl = mSharedPreferencesServer.getRequestUrl(isEdit ? UrlInfo.URL_HIDDEN_EDIT_ACTION : UrlInfo.URL_HIDDEN_NEW_ACTION);
        Logger.i(serverUrl);
        Logger.i(params.toString());
        OkHttpUtils.post().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }


//    public HiddenServices getHiddenDangerInfoListRefresh(RefreshType type, int pageSize, String hiddenType) {
//        LemonRequestParams params = new LemonRequestParams();
//        params.put("page_size", pageSize + "");
//        params.put("current_page", );
//        params.put("type", StringUtils.nullValue(hiddenType, "0"));
//        return this.getHiddenDangerInfoList(type, params);
//    }

    public HiddenServices getHiddenDangerInfoList(RefreshType type, int pageSize, int currentPage, String hiddenType) {
        LemonRequestParams params = new LemonRequestParams();
        params.put("page_size", pageSize + "");
        params.put("current_page", currentPage + "");
        params.put("type", StringUtils.nullValue(hiddenType, "0"));
        return this.getHiddenDangerInfoList(type, params);
    }

    /**
     * 获取隐患列表信息
     *
     * @param params
     * @return
     */
    public HiddenServices getHiddenDangerInfoList(RefreshType type, LemonRequestParams params) {
        HandlerCallback<List<HiddenDangerInfo>> callback = new HandlerCallback<List<HiddenDangerInfo>>(EventTag.TAG_HIDDEN_DANGER_LIST) {
        };
        callback.setOther(type);
        if (!AppUtils.isNetworkAvailable(IApplication.context())) {//如果网络不正常,这里就获取本地
            callback.localCallBack(getAllLocalHiddenDangerInfo());
            return this;
        }
        callback.setInnerCallBack(new HandlerCallback.InnerCallBack<List<HiddenDangerInfo>>() {
            @Override
            public void onInnerCallBack(List<HiddenDangerInfo> data) {
                LoggerHelper.log("test");
                saveHiddenDangerInfo(data);
            }
        });
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_DANGER_LIST);
        //Log.e("serverUrl=",serverUrl);
        //Log.e("params=",params.toString());
        OkHttpUtils.getInstance().get().tag(callback.getTag()).url(serverUrl).params(params).build().execute(callback);
        //OkHttpUtils.get().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }


    /**
     * 获取隐患列表的本地数据
     *
     * @return
     */
    public List<HiddenDangerInfo> getAllLocalHiddenDangerInfo() {
        HiddenDangerInfoDao    dao    = AppService.getDBHelper().getDaoSession().getHiddenDangerInfoDao();
        List<HiddenDangerInfo> result = dao.queryBuilder().orderDesc(HiddenDangerInfoDao.Properties.HiddenDangerId).list();
        if (result == null) {
            return new ArrayList<HiddenDangerInfo>();
        }
        return result;
    }


    /**
     * 缓存隐患列表
     *
     * @param items
     * @return
     */
    public HiddenServices saveHiddenDangerInfo(List<HiddenDangerInfo> items) {
        HiddenDangerInfoDao dao = AppService.getDBHelper().getDaoSession().getHiddenDangerInfoDao();
        try {
            if (items != null && !items.isEmpty()) {
//                dao.deleteAll();
                dao.insertOrReplaceInTx(items);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }


    /**
     * 获取隐患的附件信息
     * @param hiddenDangerId
     * @return
     */
    public HiddenServices getHiddenDangerAttestList(String hiddenDangerId) {
        LemonRequestParams params = new LemonRequestParams();
        params.put("hidden_danger_id", hiddenDangerId);
        HandlerCallback<List<UploadFileItem>> callback = new HandlerCallback<List<UploadFileItem>>(EventTag.TAG_HIDDEN_DANGER_ATTEST_LIST) {
        };
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_DANGER_ATTEST_LIST);
        OkHttpUtils.get().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }


    public HiddenServices sendZeroDanger(String companyCode) {
        LemonRequestParams params = new LemonRequestParams();
        params.put("company_code", companyCode);
        HandlerCallback<String> callback = new HandlerCallback<String>(EventTag.TAG_HIDDEN_DANGER_ZERO_ACTION) {
        };
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.URL_HIDDEN_DANGER_ZERO_ACTION);
        Logger.i(serverUrl);
        OkHttpUtils.get().url(serverUrl).tag(callback.getTag()).params(params).build().execute(callback);
        return this;
    }

}
